﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Utility
{
    public static class NetWorkHelper
    {
        public static bool PingOk(string ip)
        {
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingReply pingReply = ping.Send(ip, 200);
            if (pingReply.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool TelnetOk(string ip, int port)
        {
            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
            try
            {
                IAsyncResult result = tcpClient.BeginConnect(ip, port,null,null);
                bool success = result.AsyncWaitHandle.WaitOne(500, true);

                if(success)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                try
                {
                    tcpClient.Close();
                }
                catch { }
            }
        }

        public static bool HttpOk(string url)
        {
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            httpWebRequest.Timeout = 500;
            try
            {
                System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                if (httpWebResponse.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return true;
                }
                else
                {
                    Logger.Debug("HttpStatusCode:" + httpWebResponse.StatusCode.ToString());
                    return false;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return false; 
            }
        }
    }
}
